package com.sam.test.springboot.pool;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import javax.websocket.Session;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class MonitorService {
	 ObjectMapper mapper = new ObjectMapper();
	 /** 实时数据缓存 */
	 private static Map<String, List<Map<String, Object>>> realTimeCache = new ConcurrentHashMap<>();
	@Async("resultMonitorServiceExecutor")
	 public void resultMonitor(Future<?> result, Session session) throws InterruptedException, ExecutionException, IOException{
		while (true) {
			 if (result.isDone()&& !result.isCancelled()) {//获取future成功完成状态，如果想要限制每个任务的超时时间，取消本行的状态判断+future.get(1000*1, TimeUnit.MILLISECONDS)+catch超时异常使用即可。
                Object ret = result.get();//获取结果
                String msg = null;
                try {
                	msg = mapper.writeValueAsString(ret);
					log.info("执行结果：{}", msg);
				} catch (JsonProcessingException e) {
					e.printStackTrace();
					msg = String.valueOf(ret);
				}
                session.getBasicRemote().sendText(msg);
                break;//当前future获取结果完毕，跳出while
            } else {
                Thread.sleep(10);//每次轮询休息10毫秒（CPU纳秒级），避免CPU高速轮循耗空CPU---》新手别忘记这个
            }
		}
	}
	
	@Async("realTimeMonitorServiceExecutor")
	 public void realTimeMonitor(String message, Session session) throws InterruptedException, ExecutionException, IOException{
		while (true) {
			 if ("break".equals(message)) {//中断执行
               break;//当前future获取结果完毕，跳出while
           } else {
        	   //查询最新数据，与上轮数据比较，有变化，则将变化推送给客户端
        	   List<Map<String, Object>> oldObj = realTimeCache.get(session.getId());
        	   if (oldObj == null) {
        		   //TODO 获取数据
        		   oldObj = new ArrayList<Map<String, Object>>();
        		   Map<String, Object> map = new HashMap<>();
        		   map.put("name", "张三");
        		   oldObj.add(map);
        		   realTimeCache.put(session.getId(), oldObj);
        	   } else {
        		   //TODO 获取新数据
        		   List<Map<String, Object>> newObj = new ArrayList<Map<String, Object>>();
        		   Map<String, Object> map = new HashMap<>();
        		   map.put("name", "张三");
        		   newObj.add(map);
        		   
        		   if (newObj.size() != oldObj.size()) {//模拟数据变化
        			   String msg = null;
                       try {
	                       	msg = mapper.writeValueAsString(newObj);
	       					log.info("执行结果：{}", msg);
	       				} catch (JsonProcessingException e) {
	       					e.printStackTrace();
	       					msg = String.valueOf(newObj);
	       				}
        			   session.getBasicRemote().sendText(msg);
        			   realTimeCache.put(session.getId(), newObj);
        		   }
        	   }
               Thread.sleep(10000);//每次轮询休息10秒（CPU纳秒级），避免CPU高速轮循耗空CPU---》新手别忘记这个
           }
		}
	}
	
}
